package com.lanyou.cook.upload.service.socket.delfile;

import java.io.IOException;
import java.net.ServerSocket;

import org.apache.log4j.Logger;

import com.lanyou.cook.upload.commons.Constants;
import com.lanyou.cook.upload.util.CommUtil;
import com.lanyou.cook.upload.util.ExceptionToStrFactory;
import com.lanyou.cook.upload.util.PropFactory;

/**
 * 用于文件删除
 * 提供对ServerSocket的操作方法：
 * 1.创建ServerSocket并对指定的端口进行贞听，启动线程阻塞等待请求
 * 2.关闭ServerSocket
 * @author ly-lihailang
 *
 */
public class DelSocketServer {
	private ServerSocket serverSocket;
	private static Logger logger = Logger.getLogger(FileCilent.class); 

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new DelSocketServer().init();
	}

	/**
	 * 初始化：创建ServerSocket并对指定的端口进行贞听，启动线程阻塞等待请求
	 */
	public void init() {
		logger.info("[DelSocketServer.init]:-------------------------------------");
		try {

			String ip=CommUtil.EXECUTE_TASK_NODE;//获得本机IP

			//获取监听端口
			int acceptPort = Integer.parseInt(PropFactory
					.getPropByKey(Constants.SOCKET_SERVER_PORT_DEL));
			logger.info("[DelSocketServer.init]:ip:"+ip+"--port："+acceptPort+"服务启动");
			//创建监听端口的socket服务
			serverSocket = new ServerSocket(acceptPort);
			//创建异步线程，阻塞等待请求
			new DelListenThread(serverSocket);
		} catch (Exception e) {
			logger.error("[DelSocketServer.init]:服务器异常: " + ExceptionToStrFactory.getErrorInfoFromException(e));
		}
	}

	/**
	 * 关闭ServerSocket，在实例被销毁前执行
	 */
	public void close() {
		logger.info("[DelSocketServer.close]:----------------------------");
		try {
			//如果ServerSocket已创建实例，则将其关闭
			if (serverSocket != null) {
				serverSocket.close();
			}
		} catch (IOException e) {
			logger.error("[DelSocketServer.close]:"+ExceptionToStrFactory.getErrorInfoFromException(e));
		}
	}

}
